package org.smart4j.framework.helper;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.smart4j.framework.annotation.Action;
import org.smart4j.framework.bean.Handler;
import org.smart4j.framework.bean.Request;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Set;

/**
 *
 * 控制器助手类
 * @author luoyong
 * @date 2018-11-19下午 7:59
 */
public class ControllerHelper {

    /**
     * 用于存放 请求与处理器的映射关系(ACTION_MAP)
     */
    private static  final HashMap<Request,Handler> ACTION_MAP = new HashMap<Request, Handler>(16);

    static {

        Set<Class<?>> controllerClassSet = ClassHelper.getControllerClassSet();
        if (CollectionUtils.isNotEmpty(controllerClassSet)){
            for (Class<?> cls : controllerClassSet){
                Method[] methods = cls.getDeclaredMethods();
                if (ArrayUtils.isNotEmpty(methods)){
                    for (Method method : methods){
                        if (method.isAnnotationPresent(Action.class)){
                            Action action = method.getAnnotation(Action.class);
                            String mapping = action.value();
                            if (mapping.matches("\\w+:/\\w*")){
                                String[] array = mapping.split(":");
                                if (ArrayUtils.isNotEmpty(array) && array.length == 2){
                                    String requestMethod = array[0];
                                    String requestPath = array[1];
                                    Request request = new Request(requestMethod,requestPath);
                                    Handler handler = new Handler(cls,method);
                                    ACTION_MAP.put(request,handler);
                                }
                            }
                        }

                    }
                }
            }
        }
    }

    /***
     * 获取handler
     * @param requestMethod 请求方法
     * @param requestPath 请求路径
     * @return handler对象
     */
    public static Handler getHandler(String requestMethod,String requestPath){
        Request request = new Request(requestMethod,requestPath);
        return ACTION_MAP.get(request);

    }


}
